#include "XResample.h"
#include <QDebug>
extern "C" {
#include <libswresample/swresample.h>
#include <libavcodec/avcodec.h>
}
#pragma comment(lib,"swresample.lib")
void XResample::Close()
{
	resamplemux.lock();
	if (actx != NULL) {
		swr_free(&actx);
	}
	resamplemux.unlock();
}
bool XResample::Open(AVCodecParameters * para, bool isClearPara)
{
	if (para == NULL) {
		return false;
	}
	resamplemux.lock();
	//音频重采样 上下文初始化
	//actx = swr_alloc();
	actx = swr_alloc_set_opts(actx,
		av_get_default_channel_layout(2),	//输出格式
		(AVSampleFormat)outFormat,					//输出样本格式 1 AV_SAMPLE_FMT_S16
		para->sample_rate,					//输出采样率
		av_get_default_channel_layout(para->channels),//输入格式
		(AVSampleFormat)para->format,
		para->sample_rate,
		0, 0
	);

	if (isClearPara == true) {
		avcodec_parameters_free(&para);
	}
	//
	
	
	int re = swr_init(actx);
	resamplemux.unlock();
	qDebug() << "mux is unlock";
	if (re != 0)
	{
		char buf[1024] = { 0 };
		av_strerror(re, buf, sizeof(buf) - 1);
		qDebug() << "swr_init  failed! :" << buf;
		return false;
	}
	return true;
}



int XResample::Resample(AVFrame * indata, unsigned char * outdata)
{
	if (!indata) {
		return 0;
	}
	if (!outdata) {
		av_frame_free(&indata);
		return 0;
	}
	uint8_t *data[2] = { 0 };
	data[0] = outdata;
	int re = swr_convert(actx,
		data, indata->nb_samples,		//输出
		(const uint8_t**)indata->data, indata->nb_samples	//输入
	);
	int outSize = re * indata->channels*av_get_bytes_per_sample((AVSampleFormat)outFormat);
	av_frame_free(&indata);
	if (re <= 0) {
		qDebug() << "resample failed";
		return re;
	}
	
	
	return outSize;
}

XResample::XResample()
{
}

XResample::~XResample()
{
}
